﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ext.Net;
using System.ComponentModel;
using System.Xml.Serialization;
using Newtonsoft.Json;
using System.Data.Linq;
using System.Xml;
using System.Xml.Xsl;
using System.Reflection;
using System.IO;
using Enterprise.Resource;
namespace Enterprise.Web.Controls
{
    [DirectMethodProxyID(IDMode = DirectMethodProxyIDMode.None)]
    public partial class XGridPanel : GridPanel
    {
        private Store store;
        private Ext.Net.JsonReader reader;
        PagingToolbar pagingToolbar;
        Hidden FormatType;
        Button btnExportXML;
        Button btnExportExcel;
        Button btnExportCSV;
        Button btnAddNew;
        public XGridPanel()
        {

            this.SelectionModel.Add(new CheckboxSelectionModel
            {
                MoveEditorOnEnter = false,
                SingleSelect=true
            });
            this.BuildStore();
            this.InitLogic();
            this.BuildTopBar();
            this.BuidlBottomBar();
            this.BuildItems();
            this.BuildStyle();
        }

        private void BuildStyle()
        {
            this.TrackMouseOver = true;
            this.StripeRows = true;
        }
       
        private void BuildItems()
        {
            FormatType = new Hidden();
            FormatType.ID = "FormatType";
            this.Items.Add(FormatType);
        }

        private void BuidlBottomBar()
        {
            pagingToolbar = new PagingToolbar();
            pagingToolbar.PageSize = 20;
            
            this.BottomBar.Add(pagingToolbar);
        }

        private void BuildTopBar()
        {
            Toolbar toolbar = new Toolbar();

            btnAddNew = new Button(Resource.Resource.btnAddNew.ToString());
            btnAddNew.Icon = Icon.Add;
            btnAddNew.IconAlign = IconAlign.Left;
            toolbar.Items.Add(btnAddNew);
            toolbar.Items.Add(new ToolbarFill());
            btnExportXML = new Button(Resource.Resource.btnExportXML.ToString());
            btnExportXML.Icon = Icon.PageCode;
            
            toolbar.Items.Add(btnExportXML);
            btnExportExcel = new Button(Resource.Resource.btnExportExcel.ToString());
            btnExportExcel.Icon = Icon.PageExcel;
            toolbar.Items.Add(btnExportExcel);
            btnExportCSV = new Button(Resource.Resource.btnExportCSV.ToString());
            btnExportCSV.Icon = Icon.PageAttach;
            toolbar.Items.Add(btnExportCSV);
            this.TopBar.Add(toolbar);
        }

        private void InitLogic()
        {
            
        }

        private void BuildStore()
        {
           // this.Store.Primary.
            this.store = new Store();
            this.reader = new Ext.Net.JsonReader();
            this.reader.IDProperty = "ID";
            this.store.Reader.Add(reader);
            this.store.SubmitData += StoMainSource_Submit;
            this.store.DirectEventConfig.IsUpload = true;
            this.Store.Add(this.store);
        }

        #region public method
        public void AddGridColumn(string pIndexName, string pHeaderName)
        {
            //columnID will automatically create with prefix "col" with HeaderName
            this.ColumnModel.Columns.Add(new Column { ColumnID = "col" + pHeaderName, DataIndex = pIndexName, Header = pHeaderName });
        }

        public void AddGridColumn(string pIndexName, string pHeaderName, int pColumnWidth)
        {
            this.ColumnModel.Columns.Add(new Column { ColumnID = "col" + pIndexName, DataIndex = pIndexName, Header = pHeaderName, Width = pColumnWidth });
        }

        public void AddGridDateColumn(string pIndexName, string pHeaderName, string pDateFormat)
        {
            this.ColumnModel.Columns.Add(new DateColumn { ColumnID = "col" + pHeaderName, DataIndex = pIndexName, Header = pHeaderName, Format = pDateFormat });
        }

        public void AddGridDateColumn(string pIndexName, string pHeaderName, string pDateFormat, int pColumnWidth)
        {
            this.ColumnModel.Columns.Add(new DateColumn { ColumnID = "col" + pHeaderName, DataIndex = pIndexName, Header = pHeaderName, Format = pDateFormat, Width = pColumnWidth });
        }

        public void AddRecordField(RecordField field)
        {
            this.reader.Fields.Add(field);
        }

        public void SetDataSource(IEnumerable<object> datasource)
        {
            if (Page.IsPostBack)
            {


            }

            this.store.DataSource = datasource;
            this.store.DataBind();
        }

        public void SetPageSize(int pPageSzie)
        {
            pagingToolbar.PageSize = pPageSzie;
        }

        public void SetRowCommand(bool enableAdd, bool enableEdit, bool enableDelete, bool enabelView, bool enableCopy)
        {
            ColumnModel cm = this.ColumnModel;
            CommandColumn commandColumn = new CommandColumn();
            commandColumn.Width = 40;
            GridCommand gridCommand = new GridCommand();
            gridCommand.Icon = Icon.ArrowDown;
            if (enableAdd)
            {
                btnAddNew.Visible = true;
                MenuCommand menuCommand = new MenuCommand();
                menuCommand.Icon = (Icon)Enum.Parse(typeof(Icon), Resource.Resource.commandIconAdd.ToString());
                menuCommand.Text = Resource.Resource.commandTextAdd.ToString();
                menuCommand.CommandName = Resource.Resource.commandNameAdd.ToString();
                gridCommand.Menu.Items.Add(menuCommand);
            }
            else
            {
                btnAddNew.Visible = false;
            }

            if (enableEdit)
            {
                MenuCommand menuCommand = new MenuCommand();
                menuCommand.Icon = (Icon)Enum.Parse(typeof(Icon), Resource.Resource.commandIconEdit.ToString());
                menuCommand.Text = Resource.Resource.commandTextEdit.ToString();
                menuCommand.CommandName = Resource.Resource.commandNameEdit.ToString();
                gridCommand.Menu.Items.Add(menuCommand);
            }

            if (enableDelete)
            {
                MenuCommand menuCommand = new MenuCommand();
                menuCommand.Icon = (Icon)Enum.Parse(typeof(Icon), Resource.Resource.commandIconDelete.ToString());
                menuCommand.Text = Resource.Resource.commandTextDelete.ToString();
                menuCommand.CommandName = Resource.Resource.commandNameDelete.ToString();
                gridCommand.Menu.Items.Add(menuCommand);
            }

            if (enabelView)
            {
                MenuCommand menuCommand = new MenuCommand();
                menuCommand.Icon = (Icon)Enum.Parse(typeof(Icon), Resource.Resource.commandIconDetail.ToString());
                menuCommand.Text = Resource.Resource.commandTextDetail.ToString();
                menuCommand.CommandName = Resource.Resource.commandNameDetail.ToString();
                gridCommand.Menu.Items.Add(menuCommand);
            }

            if (enableCopy)
            {
                MenuCommand menuCommand = new MenuCommand();
                menuCommand.Icon = (Icon)Enum.Parse(typeof(Icon), Resource.Resource.commandIconCopy.ToString());
                menuCommand.Text = Resource.Resource.commandTextCopy.ToString();
                menuCommand.CommandName = Resource.Resource.commandNameCopy.ToString();
                gridCommand.Menu.Items.Add(menuCommand);
            }


            commandColumn.Commands.Add(gridCommand);
            cm.Columns.Add(commandColumn);
        }

        public void SetAutoExpandColumn(string pColumnName)
        {
            //must specify columnID.
            this.AutoExpandColumn = "col" + pColumnName;
        }

        #endregion

        #region overide method
        protected override void OnBeforeClientInit(Observable sender)
        {
            base.OnBeforeClientInit(sender);
            btnExportXML.Listeners.Click.Handler = string.Format("{0}.setValue('xml');{1}.submitData(false);nomask=true;", this.FormatType.ClientID, this.ClientID);
            btnExportExcel.Listeners.Click.Handler = string.Format("{0}.setValue('xls');{1}.submitData(false);nomask=true;", this.FormatType.ClientID, this.ClientID);
            btnExportCSV.Listeners.Click.Handler = string.Format("{0}.setValue('csv');{1}.submitData(false);nomask=true;", this.FormatType.ClientID, this.ClientID);
        }
        #endregion

        protected void StoMainSource_Submit(object sender, StoreSubmitDataEventArgs e)
        {
            string format = this.FormatType.Value.ToString();
            string strDownloadFileName = this.Title;
            XmlNode xml = e.Xml;
            Ext.Net.X.AddScript("Ext.net.Mask.hide();");
            this.Page.Response.Clear();
            switch (format)
            {
                case "xml":
                    string strXml = xml.OuterXml;
                    this.Page.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml");
                    this.Page.Response.AddHeader("Content-Length", strXml.Length.ToString());
                    this.Page.Response.ContentType = "application/xml";
                    this.Page.Response.Write(strXml);
                    break;
                case "xls":
                    this.Page.Response.ContentType = "application/vnd.ms-excel";
                    this.Page.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xls");
                    XslCompiledTransform xtExcel = new XslCompiledTransform();
                    xtExcel.Load(this.Page.Server.MapPath("~/Enterprise/Resource/Excel.xsl"));
                    xtExcel.Transform(xml, null, this.Page.Response.OutputStream);
                    break;
                case "csv":
                    this.Page.Response.ContentType = "application/octet-stream";
                    this.Page.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.csv");
                    XslCompiledTransform xtCsv = new XslCompiledTransform();
                    xtCsv.Load(this.Page.Server.MapPath("~/Enterprise/Resource/Csv.xsl"));
                    xtCsv.Transform(xml, null, this.Page.Response.OutputStream);
                    break;
            }
            this.Page.Response.End();
        }

        public enum GridCommandType
        {
            None,
            Add = 1,
            Edit = 2,
            View = 3,
            Delete = 4,
            Copy = 5
        };
    }
    
    
}
